﻿using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Web.UI;
using Microsoft.SharePoint.Utilities;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;
using System.IO;

namespace VPLink2013.Webcontrols
{
    public class FlashInfo: WebcontrolVPLink
    {
        private GlobalVPLink2013 global;

        protected override void Render(HtmlTextWriter writer)
        {
            Template = "webcontrol FlashInfo";
            try
            {
                string strHtml = string.Empty;
                string strHtmlFileCache = Path.Combine( pathCache, "FlashInfo","FlashInfo.htm" );
                FileSerialization.CheckFileCacheExists(strHtmlFileCache, 3);

                if (System.IO.File.Exists(strHtmlFileCache))
                {
                    strHtml = System.IO.File.ReadAllText(strHtmlFileCache);
                    ContextTrace.AddTrace("File cache found !");
                }
                else
                {
                    if (!string.IsNullOrEmpty(siteUrl))
                    {
                        using (SPSite site = new SPSite(siteUrl))
                        {
                            using (SPWeb web = site.RootWeb)
                            {
                                SPList lst = web.Lists.TryGetList(ListTitles.FlashInfoTitle);
                                if (lst != null)
                                {
                                    ProcessFlashInfo(lst);
                                }
                            }
                        }
                        string strXml = FileSerialization.CreateXmlStringFromObj(global);

                        string strXslFileName = "FlashInfo.xsl";
                        string strXslPath = Path.Combine(pathVP, "XSL","FlashInfo", strXslFileName);

                        ContextTrace.AddTrace("GetHtml.strXslPath = " + strXslPath);
                        strHtml = VPLink2013XsltTransformHelper.GetTransform(strXml, strXslPath, UtilisateurCrt.Login, pathTemp);
                        FileSerialization.TraceFile(strHtmlFileCache, strHtml);
                    }
                    sbHtml.AppendLine(strHtml);
                }
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("webcontrol FlashInfo.Erreur.Render : " + exc.Message);
                ContextTrace.AddTrace(exc.StackTrace);
            }
            base.Render(writer);
        }

        private void ProcessFlashInfo(SPList lst)
        {
            SPQuery spQuery = new SPQuery();
            StringBuilder sb = new StringBuilder();
			string todayDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime( DateTime.Now );
            ContextTrace.AddTrace(string.Format("date du jour : {0}", todayDate));
			sb.Append( "<Where>" );
			sb.Append( "<And>" );
			sb.Append( "<Eq><FieldRef Name='En_x0020_ligne'/><Value Type='Text'>Oui</Value></Eq>" );
			sb.Append( "<And>" );
			sb.Append( string.Format( "<Leq><FieldRef Name='Date_x0020_publication' /><Value Type='DateTime' IncludeTimeValue='True'>{0}</Value></Leq>", todayDate ) );
			sb.Append( string.Format( "<Geq><FieldRef Name='Expires' /><Value Type='DateTime' IncludeTimeValue='True' >{0}</Value></Geq>", todayDate ) );
			sb.Append( "</And>" );
			sb.Append( "</And>" );
			sb.Append( "</Where>" );
            sb.Append("<OrderBy><FieldRef Name='Date_x0020_publication' Ascending='FALSE'/><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>");
            string Query = sb.ToString();
            spQuery.Query = Query;
            ContextTrace.AddTrace("spQuery.Query : " + spQuery.Query);

            SPListItemCollection items = lst.GetItems(spQuery);

            global = new GlobalVPLink2013();
            global.FlashInfos = new List<Lien>();

            foreach (SPListItem item in items)
            {
                try
                {
                    Lien lin = CreateLink(item);
                    global.FlashInfos.Add(lin);
                }
                catch (System.Exception exc)
                {
                    ContextTrace.AddTrace("Exception lors de la creation d'un item flashinfo " + exc.Message);
                    ContextTrace.AddTrace(exc.StackTrace);
                }
            }
        }

        private Lien CreateLink(SPListItem item)
        {
            ContextTrace.AddTrace("-------------------------------");
            Lien lin = new Lien();

            string strTexteURL = item.GetItemListFieldValueAsUrlDescription(Fields.UrlNewsField);
            string strLinkURL = item.GetItemListFieldValueAsUrlValue(Fields.UrlNewsField);
            ContextTrace.AddTrace(string.Format(@"strTexteURL: {0} 
                        strLinkURL : {1}", strTexteURL, strLinkURL));

            if (!string.IsNullOrEmpty(strLinkURL))
            {
                lin.URL = strLinkURL;
            }
            else
            {
                Uri linkToAnnonce = new Uri(new Uri(siteUrl), string.Format(@"/Pages/{0}?ItemID={1}", ListNames.FlashInfoDetailName, item.ID.ToString()));
                lin.URL = linkToAnnonce.AbsoluteUri;
            }

            string strLinkImage = item.GetItemListFieldValueAsUrlValue(Fields.PhotoField);
            string strTexteImage = item.GetItemListFieldValueAsUrlDescription(Fields.PhotoField);
            ContextTrace.AddTrace("strLinkImage : " + strLinkImage);
            ContextTrace.AddTrace("strTexteImage : " + strTexteImage);
            if (strLinkImage != null)
            {
                if (strLinkImage.Length > "http://".Length)
                {
                    strLinkImage = "<img src=\"" + strLinkImage + "\" alt=\"" + strTexteImage + "\">";
                }
                else
                {
                    strLinkImage = null;
                }
                lin.Photo = strLinkImage;
            }
            lin.Titre = item.GetItemListFieldValueAsText(Fields.TitleField);
            lin.TitrePiwik = lin.Titre.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
            lin.Description = item.GetItemListFieldValueAsHtml(Fields.ChapeauNewsField);
            return lin;
        }
    }
}
